package cn.blog.controller.front;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.blog.controller.BaseServlet;
import cn.blog.service.front.LoginService;
import cn.blog.service.front.RegisterService;

@WebServlet("/front/register")
public class RegisterServlet extends BaseServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		forward("front/register");
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String email = req.getParameter("email").toString();
		String phone = req.getParameter("phone").toString();
		String uname = req.getParameter("uname").toString();
		String qqnum = req.getParameter("qqnum").toString();
		String password = req.getParameter("password").toString();

		LoginService loginService = new LoginService();
		List userNameAll = loginService.getUserNameAll();
		for (int i = 0; i < userNameAll.size(); i++) {
			if (userNameAll.get(i).equals(uname)) {
				req.getSession().setAttribute("unameLabel", " 用户名已经存在");
				redirect("/front/register");
				return;

			}
		}

		
		// 获取系统当前时间，并转换为datetime类型
		Date time = new Date();

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String t = sdf.format(time);
		java.util.Date date = null;
		try {
			date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(t);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		java.sql.Date userRegTime = new java.sql.Date(date.getTime());
		

		java.text.SimpleDateFormat ssdf = new java.text.SimpleDateFormat("MMddHHmmss");
		String Time = ssdf.format(new Date());

		String userAccount = "B" + Time;

		RegisterService regServlet = new RegisterService();
		regServlet.addUserInfo(userAccount, password, uname, null, null, phone, qqnum, email, "博主", userRegTime, 0);
		redirect("/front/login");
	}

}
